﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace SiteMapMerging
{
    public partial class FrmMain : Form
    {
        private Thread thread;
        public FrmMain()
        {
            InitializeComponent();
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {

            ConfigInfo cfg = new ConfigInfo();
            cfg.SaveFileName = txtSaveFileName.Text.Trim();
            cfg.Urls.AddRange(textBox1.Lines);
            cfg.FilterFileName = txtFilterFileName.Text.Trim();

            if (cfg.SaveFileName == "")
            {
                MessageBox.Show("保存文件不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!Directory.Exists(Path.GetDirectoryName(cfg.SaveFileName)))
            {
                MessageBox.Show("保存文件不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (cfg.FilterFileName != "" && !File.Exists(cfg.FilterFileName))
            {
                MessageBox.Show("链接过滤文件不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            ConfigMgr.Serialize(cfg);
            thread = new Thread(workService);
            thread.Start();
        }

        private HashSet<string> getFilterUrls()
        {
            HashSet<string> set = new HashSet<string>();
            string fn = txtFilterFileName.Text.Trim();
            if (File.Exists(fn))
            {
                string[] lines = File.ReadAllLines(fn, FileEncoding.Get(fn));
                foreach (string line in lines)
                {
                    string url = line.Trim().ToLower();
                    if (string.IsNullOrEmpty(url)) continue;
                    set.Add(url);
                }
            }
            return set;
        }
        private void workService()
        {
            try
            {
                foreach (Control control in this.Controls)
                    control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;

                string savefn = txtSaveFileName.Text.Trim();
                HashSet<string> list = new HashSet<string>();
                string[] lines = textBox1.Lines;
                progressBar1.Minimum = 0;
                progressBar1.Maximum = lines.Length;
                progressBar1.Value = 0;
                HashSet<string> filterUrls = getFilterUrls();
               
                foreach (string line in lines)
                {
                    progressBar1.Value += 1;
                    if (!line.Trim().StartsWith("http")) continue;
                    string html = HttpHelper.GetHtmlSource(line.Trim());
                    if (line.Trim().EndsWith(".html"))
                    {
                        string pattern = "<td><ul><li><a href=\"(?<value>.+?)\" target='_blank'>.*?</a></li></ul></td>";
                        Regex regex = new Regex(pattern);
                        MatchCollection mc = regex.Matches(html);
                        foreach (Match match in mc)
                        {
                            string url = match.Groups["value"].Value.Trim();
                            if (url.Trim() == "")
                                continue;

                            if (filterUrls.Contains(url.Trim()))
                                continue;

                            list.Add(url.Trim());
                        }
                    }
                    else if (line.Trim().EndsWith(".xml"))
                    {
                        string pattern = "<loc>(?<value>.+?)</loc>";
                        Regex regex = new Regex(pattern);
                        MatchCollection mc = regex.Matches(html);
                        foreach (Match match in mc)
                        {
                            string url = match.Groups["value"].Value.Trim();
                            if (url.Trim() == "")
                                continue;

                            if (filterUrls.Contains(url.Trim()))
                                continue;

                            list.Add(url.Trim());
                        }
                    }
                    else
                    {
                        string[] urls = html.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string url in urls)
                        {
                            if (url.Trim() == "")
                                continue;

                            if (filterUrls.Contains(url.Trim()))
                                continue;

                            list.Add(url.Trim());
                        }
                    }
                }
                File.WriteAllLines(savefn, list, Encoding.UTF8);
                MessageBox.Show("合并完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls)
                    control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            new TextBoxDragDrop(txtFilterFileName, true, new List<string>() { ".txt" });
            txtSaveFileName.ReadOnly = true;
            txtSaveFileName.BackColor = Color.White;

            Control.CheckForIllegalCrossThreadCalls = false;
            this.FormClosing += (ss, ee) =>
            {
                if (thread != null && thread.IsAlive) thread.Abort();
            };
            var cfg = ConfigMgr.DeSerialize();
            txtSaveFileName.Text = cfg.SaveFileName;
            textBox1.Lines = cfg.Urls.ToArray();
            txtFilterFileName.Text = cfg.FilterFileName;
        }

        private void btnaveFileName_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "文本文档(*.txt)|*.txt";
            dlg.DefaultExt = ".txt";
            if (dlg.ShowDialog() != DialogResult.OK) return;
            txtSaveFileName.Text = dlg.FileName;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("http://www.tianwenhai.com/");
        }

        private void btnFilterFileName_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "文本文档(*.txt)|*.txt";
            dlg.DefaultExt = ".txt";
            if (dlg.ShowDialog() != DialogResult.OK) return;
            txtFilterFileName.Text = dlg.FileName;
        }
    }
}
